package com.gzhryc.shared_device.oem.h5.mng.controllers.device;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocket;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketService;
import com.gzhryc.shared_device.cdcz.core.ICDCZNetworkService;
import com.gzhryc.shared_device.cdcz.core.models.CDCZExecuteResult;
import com.gzhryc.shared_device.common.device.dao.db.DeviceUpgradeTask;
import com.gzhryc.shared_device.common.device.dao.enums.DeviceUpgradeTaskEnum;
import com.gzhryc.shared_device.common.device.dao.models.UpgradeProcessInfo;
import com.gzhryc.shared_device.common.device.services.DeviceTypeService;
import com.gzhryc.shared_device.common.device.services.DeviceUpgradeTaskService;
import com.gzhryc.shared_device.common.device.services.dto.DeviceUpgradeTaskSearch;
import com.gzhryc.shared_device.oem.code.HttpNetworkServiceUtils;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

public class DeviceUpgradeTaskController {

    @Route(value = { "/device/upgrade/task/list.html" })
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", DeviceUpgradeTaskEnum.State.values());
        return "/device/upgrade/task/list.html";
    }

    @Route(value = "/device/upgrade/task/list.data")
    public ListResult<DeviceUpgradeTask> listData(HttpServletRequest request) {
        ListResult<DeviceUpgradeTask> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        DeviceUpgradeTaskSearch search = WebUtils.getParameter(request,DeviceUpgradeTaskSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(DeviceUpgradeTaskService.self().countJoinBySearch(search));
        result.getBody().setData(DeviceUpgradeTaskService.self().findJoinBySearch(search,pageNo,pageLimit));
        if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
        }
        return result;
    }

    @Route(value = { "/device/upgrade/task/add.html" })
    public String add(HttpServletRequest request) {
        request.setAttribute("deviceTypeList", DeviceTypeService.self().findAll());
        request.setAttribute("deviceFunCodeList", EDeviceFunCode.values());
        return "/device/upgrade/task/edit.html";
    }

    @Route(value = { "/device/upgrade/task/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        DeviceUpgradeTask deviceUpgradeTask = WebUtils.getParameter(request,DeviceUpgradeTask.class);
        try {
            if(StringTools.isNotBlank(deviceUpgradeTask.getDeviceFunCode())) {
                String deviceFunName = EDeviceFunCode.note(deviceUpgradeTask.getDeviceFunCode());
                deviceUpgradeTask.setDeviceFunName(deviceFunName);
                if (DeviceUpgradeTaskService.self().add(deviceUpgradeTask)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/device/upgrade/task/info.html" })
    public String info(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        DeviceUpgradeTask upgradeTask = DeviceUpgradeTaskService.self().getJoinById(id);
        WebUtils.setAttribute(request,upgradeTask);
        return "/device/upgrade/task/info.html";
    }

    @Route(value = "/device/upgrade/task/process/list.data")
    public ListResult<UpgradeProcessInfo.Item> processListData(HttpServletRequest request) {
        ListResult<UpgradeProcessInfo.Item> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long id = WebUtils.getLong(request,"id");
        DeviceUpgradeTask upgradeTask = DeviceUpgradeTaskService.self().getById(id);
        if(upgradeTask != null && StringTools.isNotBlank(upgradeTask.getUpgradeProcessInfo())){
            UpgradeProcessInfo processInfo = JsonTools.fromJson(upgradeTask.getUpgradeProcessInfo(),UpgradeProcessInfo.class);
            result.getBody().setData(processInfo.getItems());
        }
        if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
            result.setCode(DtoConstants.SUCCESS,null);
        }
        return result;
    }

    @Route(value = { "/device/upgrade/task/execute.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"执行失败，请稍后再试");
        Long id = WebUtils.getLong(request,"id");
        try {
            DeviceUpgradeTask upgradeTask = DeviceUpgradeTaskService.self().execute(id);
            if(upgradeTask != null){
                if(EDeviceFunCode.CDCZ.index().equals(upgradeTask.getDeviceFunCode())) {
                    ChargeSocket chargeSocket = ChargeSocketService.self().getByDeviceSn(upgradeTask.getDeviceSn());
                    if(chargeSocket == null){
                        result.setMsg("未找到充电插座设备");
                        return result;
                    }

                    ICDCZNetworkService networkService = HttpNetworkServiceUtils.getCDCZNetworkService(chargeSocket.getIotNodeId());
                    if (networkService != null) {
                    	String resDomain = WebConstants.getResDomain(request);
                        CDCZExecuteResult executeResult = networkService.upgradeDownload(chargeSocket.getDeviceSn(),WebUtils.setHttpDomain(resDomain
                                ,upgradeTask.getPackagePath()),upgradeTask.getPackageCRC());
                        if (executeResult != null) {
                            if (CDCZExecuteResult.SUCCESS.equals(executeResult.getCode())) {
                                result.setCode(DtoConstants.SUCCESS, null);
                            } else if (StringTools.isNotBlank(executeResult.getMsg())) {
                                result.setMsg(executeResult.getMsg());
                            } else {
                                result.setMsg("发送命令失败");
                            }
                        } else {
                            result.setMsg("充电插座网络服务无响应");
                        }
                    } else {
                        result.setMsg("未获取充电插座网络服务");
                    }
                }

                if(!DtoConstants.SUCCESS.equals(result.getCode())){
                    DeviceUpgradeTaskService.self().executeFail(upgradeTask,result.getMsg());
                }
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/device/upgrade/task/del.do" })
    public AjaxResult doDelete(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Long id = WebUtils.getLong(request,"id");
        try {
            if(DeviceUpgradeTaskService.self().deleteById(id)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
